import javax.microedition.media.*;
import javax.microedition.media.control.*;
import java.io.*;

public class PlayerThread extends Thread implements PlayerListener{
    
    InputStream is =null;
    String type = null;
    Player player=null;
    String fileName=null;
    PlayerThreadInvoker invoker=null;
    
    /** Creates a new instance of PlayerThread */
    public PlayerThread(PlayerThreadInvoker invoker, String filename) {
        
        this.invoker=invoker;
        this.fileName=filename;
        
    }
    public PlayerThread(PlayerThreadInvoker invoker, InputStream is, String type ) {
        
        this.invoker=invoker;
        this.is = is;
        this.type=type;
        
    }
    
    // The run method creates a player and starts the playback of the audiofile
    public void run()
    {
        try{
            if(fileName==null)
                player = Manager.createPlayer(is, type );
            else
                player = Manager.createPlayer(fileName);
            
            player.addPlayerListener(this);
            player.prefetch();
            player.realize();
            player.start();
            
        }catch(Throwable  e){
        	invoker.playerError("ERR"+e.getMessage());
        }
    }
    
    // close the player and end the playback
    public void close(){
        try{
                player.close();
                invoker.playerStopped();
                //System.out.println("playeThread.close");            
        }catch(Exception e){
        	//System.out.println(e.toString());
        }
    }
    
    // Listen to media events
    public void playerUpdate(Player player,java.lang.String event,java.lang.Object eventData){
        // When the player has started we can get the MetaDataController and send it back to the invoker ( FileBrowsingCanvas )
        if (event.equalsIgnoreCase(PlayerListener.STARTED)) {
        	invoker.playerStarted();
            MetaDataControl mc = (MetaDataControl) player.getControl(Constantes.CONTROL_METADATA);
            invoker.setMetaDataControl(mc); 
        } 
        // If the playback has reach its end we close the player and notify the invoker so it knows that the we have reached the end of the playback
        if (event.equalsIgnoreCase(PlayerListener.END_OF_MEDIA)) {
            player.close();
            invoker.playerStopped();
        }       
    }
}
